<template>
  <view>
    <view class="gapLine"></view>
    <view class="control_color">
      <view class="comments-box">
        <view class="write-comments" ref="writeComments">
          <textarea
            v-model="commentsContent"
            placeholder="发表评论"
            maxlength="5000"
            ref="commentsInput"
            auto-height
            @input="adjustHeight('commentsInput')"
          ></textarea>
          <button class="send-btn" @click="addComments">发送</button>
        </view>
        <view v-if="commentsVoListList.length > 0">
          <view
            v-for="(commentsVoList, index) in commentsVoListList"
            :key="index"
          >
            <view v-for="(commentsVo, index2) in visibleComments(commentsVoList)" :key="index2">
              <view class="comments-item" :style="{ marginLeft: index2 > 0 ? '32px' : '0' }" @click="showReplyBox(index, index2)">
                <view class="userInfo">
                  <image class="user-avatar" :src="commentsVo.simpleUserVo.avatar"></image>
                  <view class="user-name">{{commentsVo.simpleUserVo.userName}}</view>
                </view>
                <view class="commentsAndTime">
                  <view class="comments-content">
                    <text v-if="!isExpandedContent[index][index2]">{{ commentsVo.replyUserName }}{{ commentsVo.commentsContent.slice(0, 80) }}{{ commentsVo.commentsContent.length > 80 ? '...' : '' }}</text>
                    <text v-else>{{ commentsVo.replyUserName }}{{ commentsVo.commentsContent }}</text>
                  </view>
                  <view v-if="commentsVo.commentsContent.length > 80" class="toggle-expand" @click.stop="toggleExpandContent(index, index2)">
                    {{ isExpandedContent[index][index2] ? '收起' : '展开' }}
                  </view>
                  <view class="comments-time">{{ commentsVo.commentsTime }}</view>
                </view>
              </view>
              <view v-if="isReplying[index][index2]" class="reply-box">
                <textarea
                  v-model="replyContent[index][index2]"
                  placeholder="回复评论"
                  maxlength="800"
                  :ref="'replyInput-' + index + '-' + index2"
                  auto-height
                  @input="adjustHeight('replyInput-' + index + '-' + index2)"
                ></textarea>
                <button class="send-btn" @click="addReply(index, index2)">发送</button>
              </view>
            </view>
            <view v-for="(commentsVo, index2) in hiddenComments(commentsVoList)" :key="index2" v-show="isExpanded[index]">
              <view class="comments-item" :style="{ marginLeft: '32px' }" @click="showReplyBox(index, index2)">
                <view class="userInfo">
                  <image class="user-avatar" :src="commentsVo.simpleUserVo.avatar"></image>
                  <view class="user-name">{{commentsVo.simpleUserVo.userName}}</view>
                </view>
                <view class="commentsAndTime">
                  <view class="comments-content">
                    <text v-if="!isExpandedContent[index][index2]">{{ commentsVo.replyUserName }}{{ commentsVo.commentsContent.slice(0, 80) }}{{ commentsVo.commentsContent.length > 80 ? '...' : '' }}</text>
                    <text v-else>{{ commentsVo.replyUserName }}{{ commentsVo.commentsContent }}</text>
                  </view>
                  <view v-if="commentsVo.commentsContent.length > 80" class="toggle-expand" @click.stop="toggleExpandContent(index, index2)">
                    {{ isExpandedContent[index][index2] ? '收起' : '展开' }}
                  </view>
                  <view class="comments-time">{{ commentsVo.commentsTime }}</view>
                </view>
              </view>
              <view v-if="isReplying[index][index2]" class="reply-box">
                <textarea
                  v-model="replyContent[index][index2]"
                  placeholder="回复评论"
                  maxlength="800"
                  :ref="'replyInput-' + index + '-' + index2"
                  auto-height
                  @input="adjustHeight('replyInput-' + index + '-' + index2)"
                ></textarea>
                <button class="send-btn" @click="addReply(index, index2)">发送</button>
              </view>
            </view>
            <view v-if="commentsVoList.length > 2" class="show-more" @click="toggleShowMore(index)">
              {{ isExpanded[index] ? '收起' : '展开更多回复' }}
            </view>
            <view class="line"></view>
          </view>
        </view>

        <view v-else class="no-comments">暂无评论~</view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    tuanId: {
      type: Number,
      default: -1,
    },
  },
  data() {
    return {
      userId: uni.getStorageSync("userId"),
      commentsVoListList: [],
      commentsContent: "",
      isExpanded: {}, // 用于存储每个评论列表的展开状态
      isReplying: {}, // 用于存储每个评论的回复状态
      replyContent: {}, // 用于存储每个评论的回复内容
      isExpandedContent: {}, // 用于存储每个评论内容的展开状态
    };
  },

  // 使用 watch 监听 tuanId 的变化，确保在其值变化时调用 getCommentsList。
  watch: {
    tuanId(newVal) {
      if (newVal !== -1) {
        this.getCommentsList();
      }
    },
  },

  methods: {
    addComments() {
      if (this.commentsContent.trim() === "") {
        uni.showToast({
          title: "内容不能为空！",
          icon: "none",
          duration: 2000,
        });
      } else {
        uni.$http
          .post("/comments/addComments", {
            tuanId: this.tuanId,
            userId: this.userId,
            commentsContent: this.commentsContent,
            parentId: -1,
            replyUserId: -1,
          })
          .then((res) => {
            if (res.data.code === 200) {
              this.commentsContent = "";
              uni.showToast({
                title: "发表评论成功",
                icon: "none",
              });
              this.getCommentsList();
            } else {
              console.log("发表评论失败", res.data.message);
              uni.showToast({
                title: res.data.message,
                icon: "none",
              });
            }
          })
          .catch((err) => {
            console.error("发表评论失败:", err);
            uni.showToast({
              title: "发表评论失败",
              icon: "none",
            });
          });
      }
    },

    getCommentsList() {
      console.log("正在获取评论列表,tuanId:", this.tuanId);
      uni.$http
        .get(`/comments/getCommentsList?tuanId=${this.tuanId}`)
        .then((res) => {
          if (res.data.code === 200) {
            console.log("获取评论列表成功", res.data);
            this.commentsVoListList = res.data.data;
            this.commentsVoListList.forEach((list, index) => {
              this.$set(this.isExpanded, index, false); // 初始化展开状态为 false
              this.$set(this.isReplying, index, {}); // 初始化回复状态为 false
              this.$set(this.replyContent, index, {}); // 初始化回复内容为空
              this.$set(this.isExpandedContent, index, {}); // 初始化评论内容展开状态为 false
            });
          } else {
            console.log("获取评论列表失败", res.data.message);
          }
        })
        .catch((err) => {
          console.error("获取评论列表失败:", err);
        });
    },

    adjustHeight(refName) {
      this.$nextTick(() => {
        const element = this.$refs[refName];
        if (element) {
          element.style.height = "auto"; // 先重置高度
          element.style.height = element.scrollHeight + "px"; // 重新调整高度
        }

        const commentsInput = this.$refs.commentsInput;
        const writeComments = this.$refs.writeComments;
        if (commentsInput && writeComments) {
          commentsInput.style.height = "auto"; // 先重置高度
          commentsInput.style.height = commentsInput.scrollHeight + "px"; // 重新设置textarea高度

          // 根据textarea的高度设置write-message的最小高度
          writeComments.style.minHeight = commentsInput.scrollHeight + 10 + "px";
        }
      });
    },

    visibleComments(commentsVoList) {
      return commentsVoList.slice(0, 2);
    },

    hiddenComments(commentsVoList) {
      return commentsVoList.slice(2);
    },

    toggleShowMore(index) {
      this.$set(this.isExpanded, index, !this.isExpanded[index]);
    },

    showReplyBox(index, index2) {
      this.$set(this.isReplying[index], index2, true);
      this.$nextTick(() => {
        const element = this.$refs[`replyInput-${index}-${index2}`];
        if (element && element[0]) {
          element[0].focus();
        }
      });
    },

    addReply(index, index2) {
      const replyContent = this.replyContent[index][index2].trim();
      if (replyContent === "") {
        uni.showToast({
          title: "回复内容不能为空！",
          icon: "none",
          duration: 2000,
        });
      } else {
        uni.$http
          .post("/comments/addComments", {
            tuanId: this.tuanId,
            userId: this.userId,
            commentsContent: replyContent,
            parentId: this.commentsVoListList[index][index2].parentId,
            replyUserId: this.commentsVoListList[index][index2].simpleUserVo.userId,
          })
          .then((res) => {
            if (res.data.code === 200) {
              this.replyContent[index][index2] = "";
              uni.showToast({
                title: "回复成功",
                icon: "none",
              });
              this.getCommentsList();
            } else {
              console.log("回复失败", res.data.message);
              uni.showToast({
                title: res.data.message,
                icon: "none",
              });
            }
          })
          .catch((err) => {
            console.error("回复失败:", err);
            uni.showToast({
              title: "回复失败",
              icon: "none",
            });
          });
      }
    },

    toggleExpandContent(index, index2) {
      this.$set(this.isExpandedContent[index], index2, !this.isExpandedContent[index][index2]);
    },
  },
};
</script>

<style lang="scss">
.comments-box {
  padding: 10px 10px;

  .write-comments {
    display: flex;
    width: 100%;
    min-height: 38px;
    max-height: 200px; // 防止输入内容过多导致占满屏幕

    .send-btn {
      width: 70px;
      height: 34px;
      display: flex;
      margin-right: 0;
      margin-left: 10px;
      border-radius: 20px;
      font-size: 14px;
      text-align: center;
      justify-content: center;
      align-items: center;
      background-color: #fbd269;
      color: #ffffff;
    }

    textarea {
      max-height: 175px;
      width: 100%;
      padding: 6px 10px;
      border-radius: 20px;
      background-color: #f4f4f4;
      border: 1px solid rgb(213, 213, 213);
    }
  }
}

.userInfo {
    margin-top: 7px;
    display: flex;
    height: 35px;

    .user-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      margin-right: 6px;
    }
    .user-name {
      max-width: 130px; /* 设置最大宽度 */
      white-space: nowrap; /* 防止换行 */
      overflow: hidden; /* 隐藏溢出内容 */
      text-overflow: ellipsis; /* 省略号显示 */
      font-size: 13px;
      color: #616161;
    }
}

.commentsAndTime {
  margin-left: 32px;

  .comments-content {
    display: flex;
    line-height: 24px;
  }
  .comments-time {
    margin-top: 4px;
    font-size: 13px;
    color: #898989;
  }
}

.show-more {
  margin-left: 64px;
  margin-top: 10px;
  color: #2485ed;
  cursor: pointer;
}

.reply-box {
  margin-left: 64px;
  margin-top: 10px;
  display: flex;

  textarea {
    width: 100%;
    padding: 6px 10px;
    border-radius: 20px;
    background-color: #f4f4f4;
    border: 1px solid rgb(213, 213, 213);
  }

  .send-btn {
    width: 70px;
    height: 34px;
    display: flex;
    margin-left: 10px;
    border-radius: 20px;
    font-size: 14px;
    text-align: center;
    justify-content: center;
    align-items: center;
    background-color: #fbd269;
    color: #ffffff;
  }
}

.toggle-expand {
  margin-top: 5px;
  color: #2485ed;
  cursor: pointer;
}

.gapLine {
  border-top: 8px solid #f4f4f4;
}
.line {
  border-top: 1px solid #e5e5e5;
  margin-left: 32px;
  margin-top: 7px;
}
.control_color {
  background-color: #ffffff;
}
.no-comments {
  text-align: center;
  padding-top: 50px;
  color: #898989;
}
</style>